<template>
  <div ref="vtkContainer" class="vtk-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import axios from 'axios'
import * as vtk from '@kitware/vtk.js'
import * as vtkRendering from '@kitware/vtk.js/Rendering'
import * as vtkRenderingCore from '@kitware/vtk.js/Rendering/Core'
import vtkFullScreenRenderWindow from '@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow'



const props = defineProps(['filename'])
const vtkContainer = ref(null)

// VTK相关对象
let renderer = null
let renderWindow = null
let interactor = null
let container = null
let actor = null





// ✅ 动态导入 VTK.js 核心模块（避免初始化错误）
onMounted(async () => {

  // 动态加载 VTK 核心模块
  const vtk = await import('@kitware/vtk.js');
  await import('@kitware/vtk.js/Rendering/OpenGL/RenderWindow');
  
  initVtk(vtk); // 传入加载后的 vtk 对象
});


// import { createRenderer, createRenderWindow, createRenderWindowInteractor } from '@kitware/vtk.js/Rendering/Misc';
// import { createActor, createMapper } from '@kitware/vtk.js/Rendering/Core';
// import { createConeSource } from '@kitware/vtk.js/Sources/Misc';

// onMounted(() => {
//   // 创建渲染器
//   const renderer = createRenderer();
//     // 创建渲染窗口
//     const renderWindow = createRenderWindow();
//     // 将渲染器添加到渲染窗口
//     renderWindow.addRenderer(renderer);
//     // 创建渲染窗口交互器
//     const renderWindowInteractor = createRenderWindowInteractor(renderWindow);
    
//     // 创建一个锥形源
//     const coneSource = createConeSource();
//     // 创建一个映射器，它将数据源映射到几何形状
//     const coneMapper = createMapper();
//     coneMapper.setInputConnection(coneSource.getOutputPort());
    
//     // 创建一个 actor，它将映射器和属性组合在一起，用于显示几何形状
//     const coneActor = createActor();
//     coneActor.setMapper(coneMapper);
    
//     // 将 actor 添加到渲染器中
//     renderer.addActor(coneActor);
    
//     // 设置背景颜色和初始化渲染窗口的大小
//     renderer.setBackgroundColor(0, 0, 0); // 黑色背景
//     renderWindow.setSize(800, 600); // 设置窗口大小
    
//     // 初始化交互器并开始渲染循环
//     renderWindowInteractor.initialize();
//     renderWindowInteractor.start();
//   });


onBeforeUnmount(() => {
  if (renderWindow) {
    renderWindow.delete(); // 释放 VTK 资源
    renderWindow = null;
  }
});

// 初始化VTK环境
const initVtk = (vtk) => {
  // 添加空值检查
  if (!vtk) {
    console.error("VTK 模块未正确加载");
    return;
  }

  if(!vtkRendering) {//if (!vtk.Rendering) {
    console.error("VTK Core: Rendering模块未正确加载");
    return;
  }
  if(!vtkRenderingCore) { //if (!vtk.Rendering.Core) {
    console.error("VTK Core: Rendering.Core模块未正确加载");
    return;
  }
  if (!vtkContainer.value) {
    console.error("VTK Core: vtkContainer 模块未正确加载");
    return;
  }

  const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
    background: [0, 0, 0],
  });
  
  //renderer = vtkRenderingCore.vtkRenderer.newInstance()
  renderer = fullScreenRenderer.getRenderer();
  //renderWindow = vtkRenderingCore.vtkRenderWindow.newInstance()
  renderWindow = fullScreenRenderer.getRenderWindow();
  //interactor = vtkRenderingCore.vtkRenderWindowInteractor.newInstance()
  interactor = fullScreenRenderer.getInteractor();
  
  renderWindow.addRenderer(renderer)
  //interactor.setRenderWindow(renderWindow)
  interactor.setView(renderWindow)
  interactor.initialize()
  
  container = fullScreenRenderer.getContainer()
  vtkContainer.value.appendChild(container)
}

// 加载并渲染VTK文件
const loadVtkFile = async () => {
  if (!props.filename || !renderer) return
  
  try {
    // 清理旧对象
    if (actor) {
      renderer.removeActor(actor)
      actor.delete()
    }
    
    // 获取VTK文件
    const response = await axios.get(
      `http://localhost:5000/api/vtk-file/content/${props.filename}`,
      { responseType: 'arraybuffer' }
    )
    
    // 解析VTK数据
    const arrayBuffer = response.data
    const vtkReader = vtk.IO.Core.vtkPolyDataReader.newInstance()
    vtkReader.parseAsArrayBuffer(arrayBuffer)
    
    // 创建管线
    const mapper = vtk.Rendering.Core.vtkMapper.newInstance()
    mapper.setInputConnection(vtkReader.getOutputPort())
    
    actor = vtk.Rendering.Core.vtkActor.newInstance()
    actor.setMapper(mapper)
    
    // 添加到渲染器
    renderer.addActor(actor)
    renderer.resetCamera()
    renderWindow.render()
    
  } catch (error) {
    console.error('加载VTK文件失败:', error)
  }
}

</script>

<style scoped>
.vtk-container {
  flex-grow: 1;
  height: 100vh;
}
</style>